package com.efounder.chat.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.chat.R;
import com.efounder.chat.adapter.AddFriendsUserListAdapter;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.AddFriendUser;
import com.efounder.chat.model.Constant;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;

import java.util.ArrayList;
import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_ADDRESS;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PATH;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PORT;
import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;

/**
 * 弃用 查看 addallTypeFriends
 * @author yqs
 */
@Deprecated
public class AddFriendsTwoActivity extends BaseActivity {

    private String uid;
    private String TAG = "AddFriendsTwoActivity";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addfriends_two);

        final RelativeLayout re_search = (RelativeLayout) this
                .findViewById(R.id.re_search);
        final TextView tv_search = (TextView) re_search
                .findViewById(R.id.tv_search);
        final EditText et_search = (EditText) this.findViewById(R.id.et_search);

        et_search.setHint(ResStringUtil.getString(R.string.wrchatview_search_name));


        et_search.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.length() > 0) {
                    re_search.setVisibility(View.VISIBLE);
                    tv_search.setText(et_search.getText().toString().trim());
                } else {

                    re_search.setVisibility(View.GONE);
                    tv_search.setText("");

                }

            }

            public void beforeTextChanged(CharSequence s, int start, int count,int after) {
            }

            public void afterTextChanged(Editable s) {

            }
        });
        re_search.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                uid = et_search.getText().toString().trim();
                if (uid == null || uid.equals("")) {
                    return;
                }
                if (!isNetActive()) {//无网络
                    ToastUtil.showToast(AddFriendsTwoActivity.this, ResStringUtil.getString(R.string.network_anomalies));
                    return;
                }
                new AsyncTask<Void, Void, JResponseObject>() {

                    @Override
                    protected void onPreExecute() {
                        showLoading(ResStringUtil.getString(R.string.wrchatview_looking_for_contacts));
                        super.onPreExecute();
                    }

                    @Override
                    protected JResponseObject doInBackground(Void... params) {

                        // TODO 调用后台接口，查找联系人
                        // Thread.sleep(2000);

                        JParamObject PO = JParamObject.Create();
                        EAI.Protocol = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE);

                        EAI.Server = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS);
                        EAI.Port = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT);// "8085";
                        EAI.Path = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH);// "EnterpriseServer";
                        EAI.Service = Constant.EAI_SERVICE;

                        JResponseObject RO = null;
                        PO.SetValueByParamName("method", "search");
                        PO.SetValueByParamName("searchName", uid);
                        PO.SetValueByParamName("chatUserId", EnvironmentVariable.getProperty(CHAT_USER_ID, ""));
                        PO.SetValueByParamName("chatPassword", EnvironmentVariable.getProperty(CHAT_PASSWORD, ""));
                        PO.SetValueByParamName("APPID", EnvironmentVariable.getProperty("APPID"));
                        try {
                            // 连接服务器
                            String serverKey = EnvironmentVariable.getProperty("ServerKey");
                            RO = EAI.DAL.SVR(serverKey, PO);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        return RO;
                    }

                    @Override
                    protected void onPostExecute(JResponseObject result) {
                       dismissLoading();
                        if (result != null) {
                            // {F_SYBB=0, F_KSRQ=, F_CRDATE=2016-7-29.16.37. 10.
                            // 0,
                            // F_CHDATE=2016-7-29.16.37. 10. 0, F_IP=, F_CPWD=0,
                            // F_IM_PASSWORD=3.1415926,
                            // F_MACA=, F_PASS1=, _Self_RowSet=, F_CERT=,
                            // F_JSRQ=, F_YHZT=0,
                            // F_MASK=, F_SYKM=0, F_EMAIL=785072254@qq.com,
                            // F_ISROLE=0,
                            // F_PASS=NzZSNCsvZyE7RWQ2KWY9KEcoMCU=, F_MANA=0,
                            // F_TYBZ=0,
                            // F_CPRQ=, F_BZ=, F_IPKZ=0, F_CRUSER=,
                            // F_NAME=style, F_PHONE=18366103362,
                            // F_SQMS=1, F_FC=0, F_REMOTE=0, F_CERTENABLE=,
                            // F_IM_USERID=19, F_YSQX=0,
                            // F_ZGBH=18366103362, F_MESSAGE=, SQMS=0, F_SYZT=1}
                            EFDataSet efDataSet = (EFDataSet) result
                                    .getResponseObject();
                            List<EFRowSet> list = efDataSet.getRowSetArray();
                            if (list == null) {
                                return;
                            }
                            // TODO 如果返回一条数据，直接跳转； 如果返回多条，生成列表
                            List<AddFriendUser> users = new ArrayList<AddFriendUser>();
                            for (EFRowSet efRowSet : list) {
                                if (efRowSet.hasKey("tip")) {
                                    Toast.makeText(AddFriendsTwoActivity.this, ResStringUtil.getString(R.string.wrchatview_no_search_user), Toast.LENGTH_LONG).show();
                                    return;
                                }
                                AddFriendUser user = new AddFriendUser();
                                String userName = efRowSet.getString("F_NAME", "");
                                String userId = efRowSet.getString("F_IM_USERID", "");
                                String ZGBH = efRowSet.getString("F_ZGBH", "");
                                String phone = efRowSet.getString("F_PHONE", "");
                                String adName = efRowSet.getString("F_EMAIL", "");
                                String avatarUrl = efRowSet.getString("avatar", "");
                                user.setName(userName);
                                user.setAdName(adName);
                                user.setTelphone(phone);
                                user.setNumber(ZGBH);
                                user.setAvatar(avatarUrl);
                                if (!avatarUrl.equals("")) {
                                    Log.i(TAG, avatarUrl);
                                }
                                try {
                                    user.setId(Integer.valueOf(userId));
                                    users.add(user);
                                } catch (NumberFormatException e) {
                                    e.printStackTrace();
                                }
                            }
                            generateListView(users);
                        }
                    }

                }.execute();


            }

        });

    }

    private void generateListView(final List<AddFriendUser> users) {
        if (users.size() == 1) {
            User isExists = WeChatDBManager.getInstance().getOneFriendById(users.get(0).getId());
            //查询数据库属否存在该好友，如果得到的昵称跟id相同，说明不存在该好友
            if (isExists.getNickName().equals(String.valueOf(users.get(0).getId()))) {


                Intent intent = new Intent(AddFriendsTwoActivity.this,
                        AddFriendUserDetailActivity.class);
                intent.putExtra("user", users.get(0));
                startActivity(intent);
                AddFriendsTwoActivity.this.finish();

            } else {//本地存在该好友

                Intent intent = new Intent();
                intent.putExtra("id", users.get(0).getId());

                ChatActivitySkipUtil.startUserInfoActivity(AddFriendsTwoActivity.this,intent);
                AddFriendsTwoActivity.this.finish();
            }

            return;

        }
        ListView listView = (ListView) findViewById(R.id.listView_addfriend);
        AddFriendsUserListAdapter adapter = new AddFriendsUserListAdapter(users);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                Intent intent = new Intent(AddFriendsTwoActivity.this,AddFriendUserDetailActivity.class);
                intent.putExtra("user", users.get(position));
                startActivity(intent);
                AddFriendsTwoActivity.this.finish();
            }
        });

    }

    @Override
    public void back(View view) {
        finish();
    }

}